package com.zrkizzy.generator.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrkizzy.common.core.domain.response.PageResult;
import com.zrkizzy.common.core.domain.response.Result;
import com.zrkizzy.common.core.enums.CommonErrorCode;
import com.zrkizzy.common.core.utils.ServletUtil;
import com.zrkizzy.common.core.utils.bean.BeanCopyUtil;
import com.zrkizzy.generator.dto.GenerateOptionDTO;
import com.zrkizzy.generator.domain.GenerateLog;
import com.zrkizzy.generator.query.GenerateLogQuery;
import com.zrkizzy.generator.service.IGenerateLogService;
import com.zrkizzy.generator.service.IGenerateService;
import com.zrkizzy.generator.vo.GenerateLogVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 代码生成日志数据返回对象
 *
 * @author zhangrongkang
 * @since 2024/1/15
 */
@Tag(name = "代码生成日志控制器")
@RestController
@RequestMapping("/admin/generate-log")
public class GenerateLogController {

    @Autowired
    private IGenerateLogService generateLogService;

    @Autowired
    private IGenerateService generateService;

    @Operation(summary = "获取所有代码生成日志")
    @PostMapping("/list")
    public Result<PageResult<GenerateLogVO>> listGenerateLogs(@RequestBody GenerateLogQuery generateLogQuery) {
        // 查询到对应的代码生成日志集合
        Page<GenerateLog> generateLogPage = generateLogService.listGenerateLogs(generateLogQuery);
        // 处理对应数据集合并返回数据
        return Result.ok(PageResult.<GenerateLogVO>builder().total(generateLogPage.getTotal())
            .list(BeanCopyUtil.copyList(generateLogPage.getRecords(), GenerateLogVO.class)).build());
    }

    @Operation(summary = "批量删除代码生成日志")
    @DeleteMapping("/delete")
    public Result<Boolean> delete(@RequestBody List<Long> ids) {
        return generateLogService.deleteBatch(ids) ? Result.ok() : Result.failure(CommonErrorCode.INTERNAL_SERVER_ERROR, "代码生成日志数据删除失败");
    }

    @Operation(summary = "根据生成日志下载代码")
    @GetMapping("/download/{id}")
    public void download(@PathVariable Long id) {
        GenerateLog generateLog = generateLogService.getGenerateLogById(id);
        byte[] result = generateService.download(BeanCopyUtil.copy(generateLog, GenerateOptionDTO.class));
        ServletUtil.setZipServletResponse(result);
    }
}
